import { mapGetters } from "vuex";
import Tab from "vux/src/components/tab/tab.vue";
import TabItem from "vux/src/components/tab/tab-item.vue";
import Marquee from "vux/src/components/marquee/marquee.vue";
import MarqueeItem from "vux/src/components/marquee/marquee-item.vue";
import template from "./guagualeTemplate";
const { render, staticRenderFns } = template;

export default {
  render,
  staticRenderFns,
  components: {
    Tab,
    TabItem,
    Marquee,
    MarqueeItem,
  },
  data() {
    return {
      showStep1: true,
      introShow: true, //说明和奖品切换
      ruleShow: false, //活动规则显示
      congratulation: false, //中奖结果
      gameTime: 0, //游戏次数
      indexMsg: null, //首页数据
      rules: null, //活动规则
      myAward: null, //我的奖品
      page: 1,
      result: {}, //开奖结果
      id: 0,
      haveChance: true,
      pullUpLoad: false,
      browserkernel: "", //浏览器内核
      templateNum: "",
      styleTemplate: null,
    };
  },
  computed: {
    ...mapGetters(["platformConfig"]),
  },
  created() {
    document.title = "刮刮乐";
    this._getActivityBack();
    this.browserRedirect();
    this.id = this.$route.query.id;
    if (this.id) {
      this._getIndex();
      this._getRules();
    }
  },
  mounted() {
    let that = this;
    window.onresize = () => {
      clearTimeout(that.browserTime);
      that.browserTime = setTimeout(() => {
        that.browserRedirect();
      }, 400);
    };
  },
  methods: {
    _getActivityBack() {
      let vm = this;
      let params = {};
      params.type = 4;
      vm.$http
        .post(vm.urlRequest + "?m=api&c=app&a=getActivityBack", params)
        .then((res) => {
          this.templateNum = res.data;
          console.log("风格模板：", res.data);
        });
    },
    playAgain() {
      this.page = 1;
      this._getRules();
      this.initCvs();
      this._getIndex();
      this.showStep1 = true;
      this.congratulation = false;
    },
    goGuaJiang: function () {
      if (this.gameTime == 0) {
        this.$vux.toast.text("抱歉，您没有抽奖次数", "bottom");
        return;
      }
      if (this.haveChance) {
        this.showStep1 = false;
        this._getLucDraw();
      } else {
        this.$vux.toast.text("抱歉，您没有抽奖次数", "bottom");
      }
    },
    browserRedirect() {
      let sUserAgent = navigator.userAgent.toLowerCase();
      let bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
      let bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
      let bIsMidp = sUserAgent.match(/midp/i) == "midp";
      let bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
      let bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
      let bIsAndroid = sUserAgent.match(/android/i) == "android";
      let bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
      let bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
      if (
        bIsIpad ||
        bIsIphoneOs ||
        bIsMidp ||
        bIsUc7 ||
        bIsUc ||
        bIsAndroid ||
        bIsCE ||
        bIsWM
      ) {
        this.browserkernel = "h5";
      } else {
        this.browserkernel = "pc";
      }
      setTimeout(() => {
        this.initCvs();
      });
    },
    initCvs: function () {
      var that = this;
      var mpCvs = document.getElementById("mpCvs");
      var rstBox = document.getElementById("rstBox");
      mpCvs.setAttribute("class", "");
      mpCvs.width = rstBox.clientWidth;
      mpCvs.height = rstBox.clientHeight;
      var ctx = mpCvs.getContext("2d");
      var oLeft = that.getElementLeft(mpCvs);
      var oTop = that.getElementTop(mpCvs);
      var isStart = false;
      var textLeftOst = mpCvs.width / 2,
        textToptOst = mpCvs.height / 2;
      ctx.fillStyle = "silver";
      ctx.fillRect(0, 0, mpCvs.width, mpCvs.height);
      mpCvs.addEventListener("touchstart", function () {
        isStart = true;
        ctx.lineWidth = 10;
        ctx.moveTo(
          event.touches[0].clientX - oLeft,
          event.touches[0].clientY - oTop + window.pageYOffset
        );
      });
      mpCvs.onmousedown = function (e) {
        isStart = true;
        ctx.lineWidth = 10;
        ctx.moveTo(
          event.clientX - oLeft,
          event.clientY - oTop + window.pageYOffset
        );
      };
      mpCvs.addEventListener("touchend", function () {
        isStart = false;

        ctx.globalCompositeOperation = "source-over";
      });
      mpCvs.onmouseup = function (e) {
        isStart = false;

        ctx.globalCompositeOperation = "source-over";
      };
      mpCvs.addEventListener("touchmove", function (e) {
        ctx.globalCompositeOperation = "destination-out";
        if (isStart) {
          ctx.lineTo(
            event.touches[0].clientX - oLeft,
            event.touches[0].clientY - oTop + window.pageYOffset
          );
          ctx.stroke();
          /* 获取imageData对象*/
          var imageDate = ctx.getImageData(
            0,
            0,
            mpCvs.width,
            mpCvs.height
          ); /* */
          var allPX = imageDate.width * imageDate.height;
          var iNum = 0;
          for (var i = 0; i < allPX; i++) {
            if (imageDate.data[i * 4 + 3] == 0) {
              iNum++;
            }
          }
          if (iNum >= allPX * 0.5) {
            mpCvs.setAttribute("class", "disappear");
            that.congratulation = true;
          }
        }
      });
      mpCvs.onmousemove = function (e) {
        ctx.globalCompositeOperation = "destination-out";
        if (isStart) {
          ctx.lineTo(
            event.clientX - oLeft,
            event.clientY - oTop + window.pageYOffset
          );
          ctx.stroke();
          /* 获取imageData对象*/
          var imageDate = ctx.getImageData(
            0,
            0,
            mpCvs.width,
            mpCvs.height
          ); /* */
          var allPX = imageDate.width * imageDate.height;
          var iNum = 0;
          for (var i = 0; i < allPX; i++) {
            if (imageDate.data[i * 4 + 3] == 0) {
              iNum++;
            }
          }
          if (iNum >= allPX * 0.5) {
            mpCvs.setAttribute("class", "disappear");
            that.congratulation = true;
          }
        }
      };
      mpCvs.onmouseleave = function (e) {};
    },
    getElementLeft: function (element) {
      var actualLeft = element.offsetLeft;
      var current = element.offsetParent;
      while (current !== null) {
        actualLeft += current.offsetLeft;
        current = current.offsetParent;
      }
      return actualLeft;
    },
    getElementTop: function (element) {
      var actualTop = element.offsetTop;
      var current = element.offsetParent;
      while (current !== null) {
        actualTop += current.offsetTop;
        current = current.offsetParent;
      }
      return actualTop;
    },
    ruleHide() {
      this.introShow = true;
      this.ruleShow = false;
    },
    tabChange(index) {
      if (index == 0) {
        this.introShow = true;
        this.pullUpLoad = false;
        setTimeout(() => {
          this.$refs.scroll.initScroll();
        }, 20);
      } else {
        this.introShow = false;
        this.pullUpLoad = true;
        setTimeout(() => {
          this.$refs.scroll.initScroll();
        }, 20);
      }
    },
    pullingDown() {
      this.page = 1;
      this._getRules();
    },
    pullingUp() {
      if (this.pullUpLoadFlag) {
        this.$refs.scroll.forceUpdate(false);
        return;
      }
      this.page += 1;
      this._getRules();
    },
    _getRules() {
      let vm = this;
      let params = {};
      params.id = vm.id;
      params.type = 5;
      params.page = vm.page;
      vm.pullUpLoadFlag = false;
      vm.$http
        .post(vm.urlRequest + "?m=web&c=activity&a=nineRole", params)
        .then((res) => {
          if (res.status == 0) {
            vm.rules = res.result;
            if (vm.page == 1) {
              vm.myAward = res.result.list;
            } else {
              vm.myAward = vm.myAward.concat(res.result.list);
            }

            if (res.result.list.length < 20) {
              vm.pullUpLoadFlag = true;
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    _getIndex() {
      let vm = this;
      let params = {};
      params.id = vm.id;
      params.type = 5;
      vm.$vux.loading.show();
      vm.$http
        .post(vm.urlRequest + "?m=web&c=activity&a=nineIndex", params)
        .then((res) => {
          if (res.status == 0) {
            vm.indexMsg = res.result;
            vm.gameTime = vm.indexMsg.num;
          }
          vm.$vux.loading.hide();
        })
        .catch((err) => {
          vm.$vux.loading.hide();
          console.log(err);
        });
    },
    _getLucDraw() {
      let vm = this;
      let params = {};
      params.id = vm.id;
      params.type = 5;
      vm.$http
        .post(vm.urlRequest + "?m=web&c=activity&a=nineLucDraw", params)
        .then((res) => {
          if (res.status == 0) {
            vm.result = res.result;
            vm.gameTime = vm.result.num;
          } else {
            if (res.ret_msg && res.ret_msg != "") {
              vm.$vux.toast.text(res.ret_msg, "bottom");
            }
            vm.haveChance = false;
          }
        })
        .catch((err) => {
          vm.$vux.toast.text("抽奖信息错误，请重试", "bottom");
          console.log(err);
        });
    },
  },
  watch: {
    browserkernel(obj) {
      let vm = this;
      if (vm.templateNum == 2) {
        //端午节风格
        vm.styleTemplate = obj == "h5" ? "mobileStyle1" : "pcStyle1";
      } else if (vm.templateNum == 4) {
        //春节风格
        vm.styleTemplate = obj == "h5" ? "mobileStyle2" : "pcStyle2";
      }
    },
    templateNum(val) {
      let vm = this;
      if (val == 2) {
        vm.styleTemplate =
          vm.browserkernel == "h5" ? "mobileStyle1" : "pcStyle1";
      }
      if (val == 4) {
        vm.styleTemplate =
          vm.browserkernel == "h5" ? "mobileStyle2" : "pcStyle2";
      }
    },
    platformConfig(obj) {
      if (obj.platform_name) {
        document.title = "刮刮乐";
      }
    },
  },
  beforeDestroy() {},
};

// WEBPACK FOOTER //
// ./src/components/activityCenter/guaguale/guaguale.vue
